#include <QtGui>
#include <QtWebKit>
#include <QWebHistory>
#include <QDataStream>
#include "browser.h"

Browser::Browser(const QUrl& url)
{
    progress = 0;

    QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);

    QFile file;
    file.setFileName(":/jquery.min.js");
    file.open(QIODevice::ReadOnly);
    jQuery = file.readAll();
    file.close();

    QNetworkProxyFactory::setUseSystemConfiguration(true);

    view = new QWebView();
    view->load(url);
    connect(view, SIGNAL(loadFinished(bool)), SLOT(adjustLocation()));
    connect(view, SIGNAL(titleChanged(QString)), SLOT(adjustTitle()));
    connect(view, SIGNAL(loadProgress(int)), SLOT(setProgress(int)));
    connect(view, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));
    connect(view->page(), SIGNAL(downloadRequested(const QNetworkRequest&)), this, SLOT(downloadRequested(const QNetworkRequest&)));

    locationCombo = new QComboBox();
    locationCombo->setEditable(true);
    locationCombo->setSizePolicy(QSizePolicy::Expanding, locationCombo->sizePolicy().verticalPolicy());
    connect(locationCombo->lineEdit(),SIGNAL(returnPressed()),SLOT(changeLocation()));

    home = new QPushButton();

    QPixmap pixmap("projectm.ico");
    QIcon ButtonIcon(pixmap);
    home->setFlat(true);
    home->setIcon(ButtonIcon);
    home->setIconSize(pixmap.rect().size());
    home->connect(home,SIGNAL(clicked()),this,SLOT(goHome()));

    QToolBar *toolBar = addToolBar(tr("Navigation"));
    toolBar->addWidget(home);
    toolBar->addAction(view->pageAction(QWebPage::Back));
    toolBar->addAction(view->pageAction(QWebPage::Forward));
    toolBar->addAction(view->pageAction(QWebPage::Reload));
    toolBar->addAction(view->pageAction(QWebPage::Stop));
    toolBar->addWidget(locationCombo);

    QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
    QAction* viewSourceAction = new QAction("Page Source", this);
    connect(viewSourceAction, SIGNAL(triggered()), SLOT(viewSource()));
    viewMenu->addAction(viewSourceAction);

    QMenu *effectMenu = menuBar()->addMenu(tr("&Effect"));
    effectMenu->addAction("Highlight all links", this, SLOT(highlightAllLinks()));

    rotateAction = new QAction(this);
    rotateAction->setIcon(style()->standardIcon(QStyle::SP_FileDialogDetailedView));
    rotateAction->setCheckable(true);
    rotateAction->setText(tr("Turn images upside down"));
    connect(rotateAction, SIGNAL(toggled(bool)), this, SLOT(rotateImages(bool)));
    effectMenu->addAction(rotateAction);

    QMenu *toolsMenu = menuBar()->addMenu(tr("&Tools"));
    toolsMenu->addAction(tr("Remove GIF images"), this, SLOT(removeGifImages()));
    toolsMenu->addAction(tr("Remove all inline frames"), this, SLOT(removeInlineFrames()));
    toolsMenu->addAction(tr("Remove all object elements"), this, SLOT(removeObjectElements()));
    toolsMenu->addAction(tr("Remove all embedded elements"), this, SLOT(removeEmbeddedElements()));

    setCentralWidget(view);
    setUnifiedTitleAndToolBarOnMac(true);
}

void Browser::viewSource()
{
    QNetworkAccessManager* accessManager = view->page()->networkAccessManager();
    QNetworkRequest request(view->url());
    QNetworkReply* reply = accessManager->get(request);
    connect(reply, SIGNAL(finished()), this, SLOT(slotSourceDownloaded()));
}

void Browser::slotSourceDownloaded()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(const_cast<QObject*>(sender()));
    QTextEdit* textEdit = new QTextEdit(NULL);
    textEdit->setSizeIncrement(480,600);
    textEdit->setAttribute(Qt::WA_DeleteOnClose);
    textEdit->show();
    textEdit->setPlainText(reply->readAll());
    reply->deleteLater();
}

void Browser::adjustLocation()
{
    locationCombo->lineEdit()->setText(view->url().toString());
}

void Browser::changeLocation()
{
    QUrl url;
    QString http = "http://";
    if(locationCombo->lineEdit()->text().contains("http://", Qt::CaseInsensitive))
    {
        url = QUrl(locationCombo->lineEdit()->text());
    }
    else
    {
        url = QUrl(http.append(locationCombo->lineEdit()->text()));
    }

    view->load(url);
    view->setFocus();
}

void Browser::goHome()
{
    QUrl url = QUrl("http://google.com");
    view->load(url);
    view->setFocus();
}

void Browser::adjustTitle()
{
    if (progress <= 0 || progress >= 100)
        setWindowTitle(view->title());
    else
        setWindowTitle(QString("%1 (%2%)").arg(view->title()).arg(progress));
}

void Browser::setProgress(int p)
{
    progress = p;
    adjustTitle();
}

void Browser::finishLoading(bool)
{
    progress = 100;
    adjustTitle();
    view->page()->mainFrame()->evaluateJavaScript(jQuery);

    rotateImages(rotateAction->isChecked());
}

void Browser::downloadRequested(const QNetworkRequest &request)
{
    qWarning("Download Request");
    QString defaultFileName = QFileInfo(request.url().toString()).fileName();
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName);
    if (fileName.isEmpty()) return;

    QNetworkRequest newRequest = request;
    newRequest.setAttribute(QNetworkRequest::User, fileName);

    if(QFile::exists(fileName))
    {
        if(QMessageBox::question(this, tr("Downloader"),
            tr("There already exists a file called %1 in "
                "the current directory. Overwrite?").arg(fileName),
                QMessageBox::Yes|QMessageBox::No, QMessageBox::No)
                == QMessageBox::No)
                return;
        QFile::remove(fileName);
    }

    dowFile = new QFile(fileName);
    if(!dowFile->open(QIODevice::WriteOnly))
    {
        QMessageBox::information(this, "Downloader",
            tr("Unable to save the file %1: %2.")
            .arg(fileName).arg(dowFile->errorString()));
        delete dowFile;
        dowFile = NULL;
        return;
    }

    progressDialog = new QProgressDialog(this);

    QNetworkAccessManager *networkManager = view->page()->networkAccessManager();
    reply = networkManager->get(newRequest);
    connect( reply, SIGNAL(finished()), this, SLOT(downloadIssueFinished()));
    connect(reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead()));
    connect( reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(downloadProgress(qint64, qint64)) );
    connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
}

void Browser::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    progressDialog->setMaximum(bytesTotal);
    progressDialog->setValue(bytesReceived);
}

void Browser::cancelDownload()
{
    downloadRequestAborted = true;
    reply->abort();
}

void Browser::downloadIssueFinished()
{
    if(downloadRequestAborted)
    {
        if(dowFile)
        {
            dowFile->close();
            dowFile->remove();
            delete dowFile;
            dowFile = NULL;
        }
        reply->deleteLater();
        progressDialog->hide();
        return;
    }
    progressDialog->hide();
    dowFile->flush();
    dowFile->close();

    if(reply->error())
    {
        //Download failed
        QMessageBox::information(this, "Download failed", tr("Failed: %1").arg(reply->errorString()));
    }

    reply->deleteLater();
    reply = NULL;
    delete dowFile;
    dowFile = NULL;
}

void Browser::downloadReadyRead()
{
    if(dowFile)
        dowFile->write(reply->readAll());
}

void Browser::highlightAllLinks()
{
    QString code = "$('a').each( function () { $(this).css('background-color', 'yellow') } )";
    view->page()->mainFrame()->evaluateJavaScript(code);
}

void Browser::rotateImages(bool invert)
{
    QString code;
    if (invert)
        code = "$('img').each( function () { $(this).css('-webkit-transition', '-webkit-transform 2s'); $(this).css('-webkit-transform', 'rotate(180deg)') } )";
    else
        code = "$('img').each( function () { $(this).css('-webkit-transition', '-webkit-transform 2s'); $(this).css('-webkit-transform', 'rotate(0deg)') } )";
    view->page()->mainFrame()->evaluateJavaScript(code);
}

void Browser::removeGifImages()
{
    QString code = "$('[src*=gif]').remove()";
    view->page()->mainFrame()->evaluateJavaScript(code);
}

void Browser::removeInlineFrames()
{
    QString code = "$('iframe').remove()";
    view->page()->mainFrame()->evaluateJavaScript(code);
}

void Browser::removeObjectElements()
{
    QString code = "$('object').remove()";
    view->page()->mainFrame()->evaluateJavaScript(code);
}

void Browser::removeEmbeddedElements()
{
    QString code = "$('embed').remove()";
    view->page()->mainFrame()->evaluateJavaScript(code);
}
